package com.xiaowen.config.security;

import com.xiaowen.tool.JsonUtils;
import com.xiaowen.tool.dto.ErrorCode;
import com.xiaowen.tool.dto.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: yf-wenhao
 * Date: 2024/9/18
 * Time: 下午4:55
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        Result<Object> objectResult = new Result<>();
        objectResult.error(ErrorCode.UNAUTHORIZED.getCode());
        objectResult.setMsg(exception.getMessage());
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_OK);
        String s = JsonUtils.toJson(objectResult);
        response.getWriter().println(s);
    }
}
